<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */

define('SOFTWARE_ID', 1);
define('SOFTWARE_NAME', 'QQAS! Free Trial');
define('SOFTWARE_VERSION', '1.0.0');
define('SOFTWARE_LINK', 'http://www.qqas.org/');
define('SOFTWARE_UPDATE_LINK', 'http://www.koogua.com/update.html');
define('SOFTWARE_PRODUCER', 'koogua Studio');
define('SOFTWARE_PRODUCER_LINK', 'http://www.koogua.com/');
define('SOFTWARE_FEEDBACK_LINK', 'http://www.koogua.com/feedback.html');

define('DB_CHARSET', 'utf8');
define('ORIG_DB_PREFIX', 'qqas_');
define('LOCK_FILE', DATA_PATH .'install.lock');
define('INSTALL_SQL_FILE', './Install/koogua_qqas.sql');

// ------------------------------------------------------------------------

/**
 * Note: Please rename this file after install
 *
 * @category	Admin
 */
class InstallAction extends Action
{


    //初始化
	public function _initialize()
    {
        if (file_exists(DATA_PATH .'install.lock'))
        {
        	$this->error(L('install_lock'));
        }
	}


	public function index()
	{
	    $this->license();
	}


	//license
	public function license()
	{
	    $this->display('license');
	}


	//安装前检测
	public function checkEnvironment()
	{
	    //PHP环境
	    $status = 1;
	    $php = PHP_VERSION;
	    $mysql = extension_loaded('mysql') ? 1 : 0;
	    $tmp = function_exists('gd_info') ? gd_info() : array();
	    $gd = empty($tmp['GD Version']) ? 0 : $tmp['GD Version'];
	    $environment = array(
	       'php' => array('item' => L('php_version'), 'minimum' => L('min_php_version'), 'recommend' => L('rec_php_version'), 'current' => PHP_VERSION),
	       'mysql' => array('item' => L('mysql_version'), 'minimum' => L('min_mysql_version'), 'recommend' => L('rec_mysql_version'), 'current' => $mysql),
	       'gd' => array('item' => L('gd_version'), 'minimum' => L('min_gd_version'), 'recommend' => L('rec_gd_version'), 'current' => $gd),
	    );
	    $this->assign('environment', $environment);

	    if (empty($mysql) || empty($gd) || version_compare($php, 5.0) < 0)
	    {
            $status = 0;
	    }

	    //目录权限
        $directory = array
        (
        	'database' => array('type' => 'file', 'path' => CONFIG_PATH .'database.php'),
        	'Html' => array('type' => 'dir', 'path' => HTML_PATH),
        	'Runtime' => array('type' => 'dir', 'path' => RUNTIME_PATH),
        	'Cache' => array('type' => 'dir', 'path' => RUNTIME_PATH .'Cache'),
        	'Admin' => array('type' => 'dir', 'path' => RUNTIME_PATH .'Cache/Admin'),
        	'Home' => array('type' => 'dir', 'path' => RUNTIME_PATH .'Cache/Home'),
        	'Data' => array('type' => 'dir', 'path' => RUNTIME_PATH .'Data'),
        	'_sqlBackups' => array('type' => 'dir', 'path' => RUNTIME_PATH .'Data/_sqlBackups'),
        	'_fields' => array('type' => 'dir', 'path' => RUNTIME_PATH .'Data/_fields'),
        	'Logs' => array('type' => 'dir', 'path' => RUNTIME_PATH .'Logs'),
        	'Temp' => array('type' => 'dir', 'path' => RUNTIME_PATH .'Temp'),
        );
        foreach ($directory as $value)
        {
            $writable = is_writable($value['path']) ? 1 : 0;
        	$value['writable'] = $writable;
        	$directories[] = $value;
        	$status &= $writable;
        }
	    $this->assign('directories', $directories);
	    $this->assign('status', $status);

	    $this->display();
	}


	//配置db信息
	public function configDatabase()
	{
	    if ($this->isPost())
	    {

	    	$link = mysql_connect($_POST['db_host'].':'.$_POST['db_port'], $_POST['db_user'], $_POST['db_pwd']);
	    	$db = mysql_select_db($_POST['db_name'], $link);
	    	if (!$link || !$db)
	    	{
	    		$this->error(mysql_error());
	    	}
            if (mysql_get_server_info() < '4.1')
            {
                $this->error('mysql_version_too_low');
            }
	    	$content = file_get_contents(CONFIG_PATH .'database.php');
        	$content = preg_replace("/'DB_HOST'\s*=>\s*'(.*?)'/is", "'DB_HOST' => '{$_POST['db_host']}'", $content);
        	$content = preg_replace("/'DB_PORT'\s*=>\s*'(.*?)'/is", "'DB_PORT' => '{$_POST['db_port']}'", $content);
            $content = preg_replace("/'DB_USER'\s*=>\s*'(.*?)'/is", "'DB_USER' => '{$_POST['db_user']}'", $content);
            $content = preg_replace("/'DB_PWD'\s*=>\s*'(.*?)'/is",  "'DB_PWD' => '{$_POST['db_pwd']}'", $content);
            $content = preg_replace("/'DB_NAME'\s*=>\s*'(.*?)'/is", "'DB_NAME' => '{$_POST['db_name']}'", $content);
            $content = preg_replace("/'DB_CHARSET'\s*=>\s*'(.*?)'/is", "'DB_CHARSET' => '". DB_CHARSET ."'", $content);
            $content = preg_replace("/'DB_PREFIX'\s*=>\s*'(.*?)'/is", "'DB_PREFIX' => '{$_POST['db_prefix']}'", $content);

            $result = file_put_contents(CONFIG_PATH .'database.php', $content);
            if (!$result)
            {
            	$this->error(L('config_file_unwritable'));
            }

            @unlink(RUNTIME_PATH .'~app.php'); //清除原有编译文件
            $this->redirect('Admin-Install/configFounder');
	    }

	    $this->display();
	}


	//配置管理帐号
    public function configFounder()
    {
        if ($this->isPost())
        {
        	if (!is_valid_username($_POST['admin_username']))
        	{
        		$this->error(L('admin_username_invalid'));
        	}
        	if (!is_valid_password($_POST['admin_password']))
        	{
        		$this->error(L('admin_pwd_invalid'));
        	}
        	if ($_POST['admin_password'] != $_POST['admin_password2'])
        	{
        		$this->error(L('admin_pwd_neq'));
        	}
        	if (!is_valid_email($_POST['admin_email']))
        	{
        		$this->error(L('admin_email_invalid'));
        	}

        	$account = array(
        	   'username' => $_POST['admin_username'],
        	   'password' => $_POST['admin_password'],
        	   'email'    => $_POST['admin_email'],
        	);
        	$parameter = array(
        	   'parameter' => kg_base64(serialize($account)),
        	   'op' => 'save',
        	);
        	$this->redirect('Admin-Install/createData', $parameter);
        }

        $Model = M();
        $tables = $Model->query("SHOW TABLES LIKE '". C('DB_PREFIX') ."%'");
        if ($tables)
        {
        	$this->assign('confirm', 1);
        }

        $this->display();
    }


    //创建数据
    public function createData()
    {
        $Model  = M();
        $User   = D('User');
        $Config = D('Config');

        if (isset($_REQUEST['op']) && 'save' == $_REQUEST['op'])
        {
            import('@.Util.SqlDump');
            $SqlDump = new SqlDump($Model);

            if (!file_exists(INSTALL_SQL_FILE))
            {
            	$this->error(L('install_sql_not_exist'));
            }

            //替换表前缀
            if (ORIG_DB_PREFIX != C('DB_PREFIX'))
            {
                $sql = file_get_contents(INSTALL_SQL_FILE);
                $sql = str_replace('`'.ORIG_DB_PREFIX, '`'.C('DB_PREFIX'), $sql);
                $tmpFile = DATA_PATH .'~tmp.sql';
                file_put_contents($tmpFile, $sql);
                $SqlDump->sql_import($tmpFile);
                unlink($tmpFile);
            }
            else
            {
                $SqlDump->sql_import(INSTALL_SQL_FILE);
            }
            $Config->updateConfigs($data);

            //加入管理帐号
            $account = unserialize(kg_base64($_GET['parameter'], 'decode'));
            $salt = kg_password_salt();
            $data = array(
                'username'      => $account['username'],
                'password'      => kg_password_encrypt($account['password'], $salt),
                'salt'          => $salt,
                'email'         => $account['email'],
                'admin_group'   => 1,
                'user_group'    => 1,
                'point_count'   => get_activity_points('register'),
                'register_date' => date('Y-m-d'),
                'register_ip'   => get_client_ip(),
            );

            $userID = $User->add($data);

            $data = array(
                'site_url'  => trim(get_site_domain().dirname($_SERVER['SCRIPT_NAME']), '/'),
    		    'site_path' => dirname($_SERVER['SCRIPT_FILENAME']),
    		    'site_setup_time' => time(),
    		    'site_founder' => $userID,
    		    'site_auth_key' => substr(md5(time()), 8, -8),
    		    'software_name' => SOFTWARE_NAME,
    		    'software_version' => SOFTWARE_VERSION,
    		    'software_link' => SOFTWARE_LINK,
    		    'software_update_link' => SOFTWARE_UPDATE_LINK,
    		    'software_producer' => SOFTWARE_PRODUCER,
    		    'software_producer_link' => SOFTWARE_PRODUCER_LINK,
            );
            $Config->updateConfigs($data);

            //生成安装锁定文件
            touch(LOCK_FILE);

            //清理文件
            import('ORG.Io.Dir');
            Dir::del(HTML_PATH);
    		Dir::del(RUNTIME_PATH .'Cache/Admin');
    		Dir::del(RUNTIME_PATH .'Cache/Home');
    		Dir::del(RUNTIME_PATH .'Temp');
    		Dir::del(RUNTIME_PATH .'Logs');

        }

        $allTables = $Model->query("SHOW TABLES LIKE '". C('DB_PREFIX') ."%'");
		foreach ($allTables as $table)
		{
			foreach ($table as $value)
			{
				$tables .= $value ."\r\n";
			}
		}
        $this->assign('tables', $tables);

        $this->display();
    }


    //回馈站点信息
    public function sendSiteInfo()
    {
        import('ORG.Net.Http');

        $User = D('User');
        $userID = get_site_config('site_founder');
        $user = $User->find($userID);

        $data = array(
            'site_url'    => get_site_config('site_url'),
            'server_ip'   => get_server_ip(),
            'setup_time'  => time(),
            'webmaster'   => $user['username'],
            'email'       => $user['email'],
            'software_id' => SOFTWARE_ID,
        );
        Http::async_request(SOFTWARE_FEEDBACK_URL, 'post', $data);
    }

}
// End  Install Class

/* End of file InstallAction.class.php */
/* Location: ./App/Lib/Action/Admin/InstallAction.class.php */